package com.econ.powercloud.ems.job;

import com.econ.powercloud.ems.aop.TimingRetryValid;
import com.econ.powercloud.ems.common.enums.TimingControlStatusEnum;
import com.econ.powercloud.ems.dal.entity.EmsTimingControl;
import com.econ.powercloud.ems.dal.entity.EmsTimingControlDetail;
import com.econ.powercloud.ems.pojo.requestVO.YkYtIssueRequestVO;
import com.econ.powercloud.ems.service.biz.EmsYkYtIssueService;
import com.econ.powercloud.ems.service.dao.EmsTimingControlDAO;
import com.econ.powercloud.ems.service.dao.EmsTimingControlDetailDAO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author : zjf
 * @Description : 定时群控群调下发处理类
 * @Date : 2023/8/10 11:36
 * @Modified by : zjf
 */
@Slf4j
@Component("scheduleGroupControlTask")
public class ScheduleGroupControlTask implements BaseTask{
    public static final String SCHEDULE_GROUP_CONTROL_TASK = "group-control-task";

    @Autowired
    private EmsTimingControlDAO emsTimingControlDAO;
    @Autowired
    private EmsTimingControlDetailDAO emsTimingControlDetailDAO;
    @Autowired
    private EmsYkYtIssueService emsYkYtIssueService;

    @Override
    @TimingRetryValid(lockName = SCHEDULE_GROUP_CONTROL_TASK, lockExtraName = "#schedulePid")
    public void execute(Integer schedulePid) {
        log.info("执行群控群调定时任务:schedulePid:" + schedulePid);
        EmsTimingControl emsTimingControl = emsTimingControlDAO.getById(schedulePid);
        if(emsTimingControl == null){
            log.warn(String.format("未找到定时控制数据,不在执行,id:%s",schedulePid));
            return;
        }
        if(!TimingControlStatusEnum.EFFECTIVE.getCode().equals(emsTimingControl.getStatus())){
            log.warn(String.format("定时控制状态不为已生效,不在执行,id:%s",schedulePid));
            return;
        }
        List<EmsTimingControlDetail> detailList = emsTimingControlDetailDAO.selectListByTimingControlId(schedulePid);
        if(CollectionUtils.isEmpty(detailList)){
            log.warn(String.format("该定时控制未配置群控群调下发点号,不在执行,id:%s",schedulePid));
            return;
        }
        List<YkYtIssueRequestVO> issueRequestVOList = detailList.stream().map(d->
                        YkYtIssueRequestVO.builder().deviceCode(d.getDeviceCode())
                                .ditType(d.getDitType()).dit(d.getDit()).val(Double.parseDouble(d.getVal())).build())
                .collect(Collectors.toList());
        emsYkYtIssueService.groupControl(issueRequestVOList,emsTimingControl.getClientIp());
    }
}
